<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { NFlex, NButton, NIcon, NMention, NInputGroup, NModal, createDiscreteApi, NGrid, NGridItem } from 'naive-ui';
import type { StepsProps } from 'naive-ui'
import ComponentsAi from '@/components/CompponentsAi.vue';
import ComponentsEasyWord from '@/components/ComponentsEasyWord.vue';
import ComponentsEasyExcel from '@/components/ComponentsEasyExcel.vue';
import ComponentsEchartsExcel from '@/components/ComponentsEchartsExcel.vue';
import ComponentsEchartsExcel3D from '@/components/ComponentsEchartsExcel3D.vue';
import ComponentsEchartsWord from '@/components/ComponentsEchartsWord.vue';
import ComponentsEcharts3D from '@/components/ComponentsEcharts3D.vue';
import SvgIcon from '../components/SvgIcon.vue'
import { AI_ADD } from "@/service/apis/from";
import { sseService } from "../assets/utils/sse";
import type { SSEChatParams } from "../assets/utils/sse";
import { sseUrl } from "@/service/sseUrl";
import iconJsonObj from '../assets/font/appiconfont.json';

const iconArray = iconJsonObj.glyphs

const { message } = createDiscreteApi(["message"])
const stepCurrent = ref(1)
const currentStatus = ref<StepsProps['status']>('process')
const mentionValue = ref("")
const active = ref(false)
const appType = ref()
const showModal = ref(false)
const chatlist = ref<any>([])
const lastConversation = ref('')
let last标识 = ''


const stepList = ["", "应用命名", "应用图标", "应用类型", "定义数据", "数据文件命名", "应用使用范围", "应用保存"]
const placeholderList = ["", "", "请输入文字 <‘图标’>获取图标库", "请输入@字符选择应用的类型", "", "请输入数据文件命名称（格式：xxx-日期）", "请输入应用使用的范围，例:部门名称、岗位名称", ""]
const options = [
    {
        label: 'word',
        value: 'word'
    },
    {
        label: 'excel',
        value: 'excel'
    },
    {
        label: 'echarts-excel',
        value: 'echarts-excel'
    },
    {
        label: 'echarts-excel-3d',
        value: 'echarts-excel-3d'
    },
    {
        label: 'echarts-3d',
        value: 'echarts-3d'
    },
    {
        label: 'echarts-word',
        value: 'echarts-word'
    },
]
const getLastUnshowChat = () => {
    const lastChat = chatlist.value[chatlist.value.length - 1]
    if (lastChat && lastChat.direction === 0) {
        return lastChat.conversation
    }

    return ""
}

/**
 * 流式显示
 */
let conversationUpdater:any
const startConversationUpdater = () => {
    conversationUpdater = setInterval(() => {
        const last = getLastUnshowChat()
        if (lastConversation.value.length < last.length) {
            lastConversation.value += last.charAt(lastConversation.value.length)
            scrollToBottom()
        }
        else {
            // clearInterval(conversationUpdater!)
        }
    }, 50)
}

onMounted(() => {
    sseServiceOpen()
    AiInit()
    setEnterKeyEvent()
    startConversationUpdater()
})

onUnmounted(() => {
    sseService.disconnect()
})

const handleEnterKey = (event:any) =>{ 
    if (event.key === 'Enter') {
        if(!mentionValue.value.trim()){
            return
        }
        if (!event.shiftKey) {
            event.preventDefault();
            console.log('提交')
            sendMsg()
        }
    }
}  
const setEnterKeyEvent = () => {
    const textarea = document.getElementById('theTextarea');  
    textarea!.addEventListener('keydown', handleEnterKey);  
}
const scrollToBottom = () => {
    setTimeout(() => {
        const scrollableDiv = document.getElementById('scrollListRef');
        if (scrollableDiv) {
            // scrollableDiv.scrollTop = scrollableDiv.scrollHeight - scrollableDiv.clientHeight;  
            scrollableDiv.scrollTop = scrollableDiv.scrollHeight;
        }
    }, 100)
} 

//see 链接
function sseServiceOpen() {
    console.log(sseService);

    const onopen = () => {
        console.log("消息菜单建立无敌 sse 连接成功")
    }
    // 建立连接
    let sseChatParams: SSEChatParams = {
        onopen,
        url: sseUrl.Ai,
        onmessage: (event: MessageEvent) => {
            // 收到消息
            console.log('收到AI对话消息：', event.data);
            const msg = event.data.replace(/\\n/g, "\n")
            if (!msg) {
                return
            }

            const msgObj = JSON.parse(msg)

            const type = msgObj.type

            if (type === 'text') {
                const conversationText = msgObj.value
                const lastChat = chatlist.value[chatlist.value.length - 1]
                // 如果当前列表中最后一条消息是用户发送的，则新消息追加到后面
                if (lastChat && lastChat.direction === 0) {
                    lastChat.conversation += ('<br>' + conversationText)
                } else {
                    chatlist.value.push({
                        direction: 0,
                        conversation: conversationText
                    })
                    lastConversation.value = ''
                }
            }
            else if (type === 'open') {     
                if(msgObj.value === 'icons'){
                    showModal.value = true
                } else {
                    active.value = true
                    appType.value = msgObj.value
                }
            }

            // const res = Papa.parse(fst, { header: true, delimiter: ";", newline: "\n" })
        //     if (event.data != '' && event.data != 'done' && event.data != 'word') {
        //         let arr = []
        //         arr.push({
        //             pos: 0,
        //             name: event.data
        //         })
        //         chatlist.value = chatlist.value.concat(arr)
        //     }
        //     if (event.data == 'done') {
        //         next()
        //         if (stepCurrent.value == 2) {
        //             showModal.value = true
        //         }
        //         if (stepCurrent.value == 7) {

        //         }
        //     }
        //     if (event.data == 'word') {
        //         active.value = true
        //         appType.value = 'word'
        //         componentFlag.value = false
        //     } else if (event.data == 'excel') {
        //         active.value = true
        //         appType.value = 'excel'
        //         componentFlag.value = false
        //     } else if (event.data == 'echarts-excel') {
        //         active.value = true
        //         appType.value = 'echarts-excel'
        //         componentFlag.value = false
        //     } else if (event.data == 'echarts-excel-3d') {
        //         active.value = true
        //         appType.value = 'echarts-excel-3d'
        //         componentFlag.value = false
        //     } else if (event.data == 'echarts-3d') {
        //         active.value = true
        //         appType.value = 'echarts-3d'
        //         componentFlag.value = false
        //     } else if (event.data == 'echarts-word') {
        //         active.value = true
        //         appType.value = 'echarts-word'
        //         componentFlag.value = false
        //     }
        //     if (event.data == '应用保存') {
        //         let p = {
        //             步骤: stepList[stepCurrent.value],
        //             内容: '应用保存',
        //             来源: "用户"
        //         }
        //         getAiSetps(p)
        //     }

        },
        finallyHandler: () => {
            console.log("finallyHandler操作")
        }
    };
    sseService.connect(sseChatParams)


}

function sendMsg() {
    console.log(mentionValue.value);
    chatlist.value.push({
        direction: 1,
        conversation: mentionValue.value
    })

    if (mentionValue.value != "图标") {
        let p = {
            "标识": last标识,
            "内容": mentionValue.value,
            "值": mentionValue.value,
        }
        getAiSetps(p)
    }
    mentionValue.value = ''
    scrollToBottom()
}

function AiInit() {
    const initParams = {
        "标识": "init",
        "内容": "",
        "值": ""
    }
    AI_ADD({ params: JSON.stringify(initParams) }).then((res: any) => {
        console.log('Init AI,返回信息',res);
        if(res.data){
            last标识 = res.data
        }
    }).catch((err) => {
        console.log(err);
    });
}

function getAiSetps(val: any) {
    AI_ADD({ params: JSON.stringify(val) }).then((res: any) => {
        console.log('消息发送,返回信息',res);
        if(res.data){
            last标识 = res.data
        }
    }).catch((err) => {
    });
}

//图标选择
function iconClick(val: any) {
    console.log(val);
    mentionValue.value = val.conversation
    // let p = {
    //     步骤: stepList[stepCurrent.value],
    //     内容: val,
    //     来源: "用户"
    // }
    let p = {
        "标识": last标识,
        "内容": val.font_class,
        "值": val.font_class
    }
    getAiSetps(p)
    mentionValue.value = ''
    showModal.value = false
}

function saveData(params: any) {
    console.log(params);
    let p = {
        "标识": last标识,
        "内容": "",
        "值": params
    }
    getAiSetps(p)
    message.success('保存成功')
    active.value = false
}

// const 少啰嗦 = () => {
//     console.log('少啰嗦');
//     lastConversation.value = getLastUnshowChat()
// }

</script>
<template>
    <components-ai title="AI智能应用创建向导" icon="zhinengAI">
        <template #header-extra>
            
        </template>
        <n-flex vertical :size="0">
            <!-- {{ chatlist }} -->
            <n-flex justify="space-between">
                <n-flex><div></div></n-flex>
                <n-flex vertical class="dialogue" id="scrollListRef" :size="[0,0]">
                    <!-- 中间内容 -->
                    <template v-for="(item, index) in chatlist">
                        <n-flex v-if="item.direction == 0" style="display: grid;  grid-template-columns: auto 1fr; margin-bottom: 5px;">
                            <n-icon :size="24" style=" ">
                                <svg-icon iconClass="huida2"></svg-icon>
                            </n-icon>
                            <span style="display: grid;  grid-template-columns: auto 1fr;">
                                <div class="robotChatBodyTip"></div>
                                <div class="robotChatBody">
                                    <div v-if="index !== chatlist.length - 1" v-html="item.conversation" style=""></div>
                                    <div v-else style="" v-html="lastConversation"></div>
                                    <NGrid :cols="15">
                                        <NGridItem class="svgBox" v-if="showModal && index === chatlist.length - 1" v-for="(j, k)  in iconArray" @click="iconClick(j)">
                                            <n-icon :size="50">
                                                <svg-icon :iconClass="j.font_class"></svg-icon>
                                            </n-icon>
                                            <!-- <div>{{ j.name }}</div> -->
                                        </NGridItem>
                                    </NGrid>
                                </div>
                                <!-- <div v-else style="" class="robotChatBody">{{ i.conversation }} </div> -->
                            </span>
                        </n-flex>
                        <n-flex v-else style="display: grid;  grid-template-columns: auto 1fr; margin-bottom: 5px;">
                            <n-icon :size="24"><svg-icon iconClass="wenda"></svg-icon></n-icon>
                            <span style="display: grid;  grid-template-columns: auto 1fr;">
                                <div class="replyChatBodyTip"></div>
                                <div class="replyChatBody">{{ item.conversation }} </div>
                            </span>
                        </n-flex>
                    </template>

                </n-flex>
                <n-flex>
                    <!-- 右侧内容 -->
                    <div></div>
                </n-flex>
            </n-flex>
        </n-flex>
        <template #action>
            <n-flex justify="center">
                <n-input-group style="justify-content: center;">
                    <n-mention id="theTextarea" :options="options" v-model:value="mentionValue"
                        :placeholder="placeholderList[stepCurrent]" type="textarea" style="width: 700px;" />
                    <n-button style="height: 80px;" type="primary" size="large" :disabled="stepCurrent >= 7"
                        @click="sendMsg">发送</n-button>
                </n-input-group>
            </n-flex>
        </template>
    </components-ai>

    <div class="easyAppBox" v-if="active">
        <ComponentsEasyWord v-if="appType === 'word-temp'" @saveData="saveData"></ComponentsEasyWord>
        <ComponentsEasyExcel v-else-if="appType === 'excel-temp'" @saveData="saveData"></ComponentsEasyExcel>
        <ComponentsEchartsExcel v-else-if="appType === 'echarts-excel'" @saveData="saveData"></ComponentsEchartsExcel>
        <ComponentsEcharts3D v-else-if="appType === 'echarts-3d'" @saveData="saveData"></ComponentsEcharts3D>
        <ComponentsEchartsExcel3D v-else-if="appType === 'echarts-excel-3d'" @saveData="saveData">
        </ComponentsEchartsExcel3D>
        <ComponentsEchartsWord v-else-if="appType === 'echarts-word'" @saveData="saveData"></ComponentsEchartsWord>
    </div>

</template>
<style scoped>
.dialogue {
    /* border: 1px solid #dcdcdc; */
    border-radius: 5px;
    padding: 2px;
    width: calc(100%/2);
    overflow-y: scroll;
    height: calc(100vh - 300px);
}
/* 整个滚动条 */  
::-webkit-scrollbar {  
    /* width: 12px;  滚动条的宽度   */
    width: 0;
}  
  
/* 滚动条轨道 */  
::-webkit-scrollbar-track {  
    background: #f1f1f1;  /* 轨道颜色 */  
}  
  
/* 滚动条滑块 */  
::-webkit-scrollbar-thumb {  
    background: #888;  /* 滑块颜色 */  
    border-radius: 10px;  /* 滑块圆角 */  
}  
  
/* 滑块在悬停时的状态 */  
::-webkit-scrollbar-thumb:hover {  
    background: #555;  /* 悬停时的颜色 */  
}

.df {
    color: #dcdcdc;
}

.topdrawer {
    height: 40px;
    width: 100%;
    /* background-color: aqua; */
    padding: 5px;
    animation: myWidth 0.2s linear;
    animation-iteration-count: 1;
    -webkit-animation: myWidth 0.2s linear;
    /* position: absolute;
    z-index: 10;
    pointer-events: none; */
}

.svglay {
    display: flex;
    flex-wrap: wrap;
    height: 600px;
    overflow-y: scroll;
}

.svgBox {
    /* height: 155px;
    width: 150px;
    margin: 30px; */
    text-align: center;
}

@keyframes myWidth {
    0% {
        height: 0;
    }

    100% {
        height: 40px;
    }
}.easyAppBox {
    position: fixed;
    top: 30px;
    left: 10%;
    right: 10%;
    height: 710px;
    background-color: #FFFFFF;
    border-radius: 5px;
    box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.5);
}

.robotChatBody {
    color: white;
    background-color: black;
    /* background-color: #f2f2f2; */
    padding: 10px;
    border-radius: 5px;
    font-size: 18px;
    font-weight: normal;
}

.robotChatBodyTip {
    margin-top: 10px;
    border-left: 10px solid #fff;
    border-top: 10px solid black;
}

.replyChatBody {
    padding: 10px;
    border-radius: 5px;
    border: #18a058 solid 2px;
    font-size: 18px;
    font-weight: normal;
}

.replyChatBodyTip {
    margin-top: 10px;
    border-left: 10px solid #fff;
    border-top: 10px solid #18a058;
}
</style>